package com.demo.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.entity.ChannelEntity;
import com.demo.entity.MdataBaseParamBo;
import com.demo.mapper.ChannelMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

/**
 * 渠道服务
 *
 * @author liuyuanqi
 * @date 2021-10-26
 */
@Slf4j
@Service
public class ChannelService extends ServiceImpl<ChannelMapper, ChannelEntity> {

    @Resource
    private ChannelMapper channelMapper;

    @Transactional(rollbackFor = Exception.class)
    public String sync(List<MdataBaseParamBo> list) {
        try {
            for (MdataBaseParamBo bo : list) {
                JSONArray array = JSON.parseArray(bo.getJsonDatas());
                array.forEach(x -> {
                    JSONObject obj = JSONObject.parseObject(x.toString());

                    ChannelEntity ce = new ChannelEntity();
                    obj.forEach((k, v) -> {
                        ce.setCode(k);
                        ce.setName(v.toString());
                    });

                    ChannelEntity old = channelMapper.selectById(ce.getCode());
                    if (old == null) {
                        channelMapper.insert(ce);
                    } else {
                        channelMapper.updateById(ce);
                    }
                });
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            return "数据重复或缺少必填字段、请检查";
        }
        return "保存成功";
    }

}
